﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using RBS.Common;
using RBS.Common.JsonEntity;
using RBS.Core.BLL;
using RBS.Web.Controllers;
using RBS.Web.Models;
using Webdiyer.WebControls.Mvc;
using D_Order_Details = RBS.Core.Model.D_Order_Details;

namespace RBS.Web.Areas.User.Controllers
{
    public class OrderController : BaseController
    {
        //
        // GET: /User/Order/

        public ActionResult OrderList(int id = 1, string kword = null)
        {
            const int pageSize = 10;
         
            var bll = new RBS.Core.BLL.D_Order();
            // var admin = GetAdminInfo(); //取得当前管理员信息
            if (kword != null) kword = kword.Replace("'", "");
            var strTemp = new StringBuilder();
            if (!string.IsNullOrEmpty(kword))
            {
                //strTemp.Append(" and (H_UID like  '%" + kword + "%' or H_UserName like '%" + kword + "%')");
            }
            string strWhere = " and u_id ="+ CurrentUser.Id+strTemp.ToString();
            const string orderby = " id  desc";
            var startIndex = id;

            int totalItems = 0; //要分页的总记录数
            DataTable dt = bll.GetList(pageSize, startIndex, strWhere, orderby, out totalItems).Tables[0];
            //PagedList构造函数 
            var list = IListDataSet.DataTableToIList<RBS.Core.Model.D_Order>(dt);
            PagedList<RBS.Core.Model.D_Order> arts = null;
            if (list != null)
                arts = new PagedList<RBS.Core.Model.D_Order>(list, id, pageSize, totalItems);
            else
            {
                list = new List<RBS.Core.Model.D_Order>();
                arts = new PagedList<RBS.Core.Model.D_Order>(list, id, pageSize, totalItems);
            }
            return View(arts);
        }


        #region 我的饭局
        
        public ActionResult MyDinner(int id = 1, string kword = null)
        {
            const int pageSize = 10;

            ViewBag.UserId = CurrentUser.Id;
            var bll = new RBS.Core.BLL.D_Order();
            // var admin = GetAdminInfo(); //取得当前管理员信息
            if (kword != null) kword = kword.Replace("'", "");
            var strTemp = new StringBuilder();
            if (!string.IsNullOrEmpty(kword))
            {
                //strTemp.Append(" and (H_UID like  '%" + kword + "%' or H_UserName like '%" + kword + "%')");
            }
            string strWhere = " and id  in (select orderid from D_Guest where guestid = " + CurrentUser.Id + " ) " +strTemp.ToString();
            const string orderby = " id  desc";
            var startIndex = id;

            
            int totalItems = 0; //要分页的总记录数
            DataTable dt = bll.GetList(pageSize, startIndex, strWhere, orderby, out totalItems).Tables[0];
            //PagedList构造函数 
            var list = IListDataSet.DataTableToIList<RBS.Core.Model.D_Order>(dt);
            PagedList<RBS.Core.Model.D_Order> arts = null;
            if (list != null)
                arts = new PagedList<RBS.Core.Model.D_Order>(list, id, pageSize, totalItems);
            else
            {
                list = new List<RBS.Core.Model.D_Order>();
                arts = new PagedList<RBS.Core.Model.D_Order>(list, id, pageSize, totalItems);
            }
            return View(arts);
        }

        public JsonResult IsParticipate(int orderid, int status, string remark="")
        { 
            var ret = new JsonReturnMessages();
            var bll = new RBS.Core.BLL.D_Guest();
            if (bll.UpdateStatus(orderid, CurrentUser.Id, status, remark))
            {
                ret.IsSuccess = true;
                ret.Msg = "操作成功";
            }
            else
            {
                ret.IsSuccess = false;
                ret.Msg = "操作失败";
            }
            return Json(ret);
        }  
        #endregion


        #region  餐桌
        public ActionResult AddSeat(int hid = 0, int orderid = -1)
        {
            if (orderid == -1)
            {
                return RedirectToAction("Detail", "Store", new { area = "", id = hid });
            }

            var model =
                new RBS.Core.BLL.Hotel.H_Hotel_Seat().GetModelList("hotelid=" + hid + " and AOBT=1  and Status=0");
            return View(model);
        } 

        //选择餐桌
        [AcceptVerbs(HttpVerbs.Post)]
        public Action AddSeatToOrder(string ids)
        {
           /* var ret = new JsonReturnMessages(); 
            try
            {
                foreach (var id in ids.TrimEnd(',').Split(',').ToList())
                {
                    new RBS.Core.BLL.Hotel.H_Hotel_Seat().Delete(int.Parse(id));
                }
            }
            catch (Exception exception)
            {
                ret.IsSuccess = false;
                ret.Msg = "操作失败！";
                return Json(ret);
            } 
            ret.IsSuccess = true;
            ret.Msg = "操作成功";
            return Json(ret);*/
            return null;
        }


        #endregion


        public ActionResult AddOrder(int hid=0,int orderid=-1)
        {
            if (orderid == -1)
            {
                return RedirectToAction("Detail", "Store", new {area="",id = hid});
            }

            var model = new RBS.Core.BLL.D_Order().GetModel(orderid);
            return View(model);
        }
        [HttpPost]
        public ActionResult AddOrder(FormCollection collection)
        {
            var a = collection;
            var model = new RBS.Core.Model.D_Order
            {
                                /*  OrderState =  collection["OrderState"],
                OrderTime =  collection["OrderTime"],
                OrderChannel =  collection["OrderChannel"],
                ContactUser =  collection["ContactUser"],
                ContactMobile =  collection["ContactMobile"],
                OrderRemark =  collection["OrderRemark"],
                OrderAmount =  collection["OrderAmount"],
                RecAmount =  collection["RecAmount"],
                DisAmount =  collection["DisAmount"],
                AccAmount =  collection["AccAmount"],
                PayType =  collection["PayType"],
                PayTime =  collection["PayTime"],
                ReserveDate =  collection["ReserveDate"],
                ReserveTime =  collection["ReserveTime"],
                DineNum =  collection["DineNum"],
                H_Id =  collection["H_Id"],
                HotelName =  collection["HotelName"],
                DineTable =  collection["DineTable"],
                Dinecondition =  collection["Dinecondition"],
                U_Id =  collection["U_Id"],
                CreateTime =  collection["CreateTime"],
                CreateUser =  collection["CreateUser"],
                LastModifyDate =  collection["LastModifyDate"],
                LastModifyUser =  collection["LastModifyUser"],
                */
            };

            var bll = new RBS.Core.BLL.D_Order();
            if (collection["Id"] != "0")
            {
                model.Id = Convert.ToInt32(collection["Id"]);
                bll.Update(model);
               
            }
            else
            {

                bll.Add(model);
          
            }
               return RedirectToAction("OrderList");
        }

        public readonly RBS.Core.BLL.D_Order Orderbll = new RBS.Core.BLL.D_Order();
        public readonly RBS.Core.BLL.Hotel.H_Hotel_Seat Seatbll = new RBS.Core.BLL.Hotel.H_Hotel_Seat();

        public readonly RBS.Core.BLL.D_Guest Guestbll = new RBS.Core.BLL.D_Guest();
        public readonly RBS.Core.BLL.V_Guest VGuestbll = new V_Guest();
        public readonly RBS.Core.BLL.SmsMessage smsMessage = new SmsMessage();
      
        
        /// <summary>
        /// 订单取消
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="returnUrl"></param>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult OrderCancel(string ids, string returnUrl)
        {
            var ret = new JsonReturnMessages(); 
            try
            {
                foreach (var id in ids.TrimEnd(',').Split(',').ToList())
                {
                    //修改订单状态
                    var model = Orderbll.GetModelByCache(Convert.ToInt32(id));
                     Orderbll.UpdateOrderStatus(Convert.ToInt32(id), (int)RBSEnums.OrderStatus.Canceled);
                    //修改座位状态 
                     Seatbll.UpdateStatus(model.H_Id, model.DineTable.ToString(), 0); 
                    //修改邀请状态 
                    var guestList=VGuestbll.GetModelList(model.Id);
                    var ymb = guestList.Aggregate("", (current, guest) => current + (guest.Mobile + ","));
                    string msg = "";
                    string content = "您的朋友在["+model.HotelName+"]预定的饭局已经取消";
                    smsMessage.Send(ymb.TrimEnd(','), content, 1, out msg);   
                    Guestbll.DeleteByOrderId(model.Id); 
                }
            }
            catch (Exception exception)
            {
                ret.IsSuccess = false;
                ret.Msg = "操作失败！";
                return Json(ret);
            } 
            ret.IsSuccess = true;
            ret.Msg = "操作成功";
            ret.Data = !string.IsNullOrEmpty(returnUrl) ? returnUrl : Url.Action("OrderList");
            return Json(ret);
        }
      
        /// <summary>
        /// 客人取消
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="returnUrl"></param>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult GuestCancel(string ids, string returnUrl)
        {
            var ret = new JsonReturnMessages(); 
            try
            {
                foreach (var id in ids.TrimEnd(',').Split(',').ToList())
                { 
                    //修改邀请状态
                    Guestbll.Delete(Convert.ToInt32(id));
                  
                }
            }
            catch (Exception exception)
            {
                ret.IsSuccess = false;
                ret.Msg = "操作失败！";
                return Json(ret);
            } 
            ret.IsSuccess = true;
            ret.Msg = "操作成功";
            ret.Data = !string.IsNullOrEmpty(returnUrl) ? returnUrl : Url.Action("Invite");
            return Json(ret);
        }
      
      

        //购物车
        public List<RBS.Core.Model.V_OrderDetails> GetModelByCache(RBS.Core.Model.V_OrderDetails m)
        {
            List<RBS.Core.Model.V_OrderDetails> list;
              if (Session[RBSKeys.SESSION_SHOPCAR_INFO] == null)  
             {
                 list = new List<RBS.Core.Model.V_OrderDetails> { m };
                 Session[RBSKeys.SESSION_SHOPCAR_INFO] = list;
             }  
             else  
             {  
                 //如果购物车不为空时 刚判断 该商品的信息是否存在购物车中 如果 存在则 把该商品的数量加上1  
                 list = Session[RBSKeys.SESSION_SHOPCAR_INFO] as List<RBS.Core.Model.V_OrderDetails>;
                 if (list != null)
                 {
                     var item = list.FirstOrDefault(c => c.HCId == m.HCId);
                     if (item == null)
                     {
                         if (m.Num > 0)
                         {
                             list.Add(m);
                         }
                     }
                     else
                     {
                         item.Num = item.Num + m.Num; 
                         if (item.Num <= 0)
                        {
                            if (item.Id != 0)
                            {
                                new RBS.Core.BLL.D_Order_Details().Delete(item.Id);
                            }
                            list.Remove(item); 
                        }  
                     } 
                     Session[RBSKeys.SESSION_SHOPCAR_INFO] = list; 
                 }
                 else
                 {
                     list.Add(m);
                     Session[RBSKeys.SESSION_SHOPCAR_INFO] = list;
                 }
             }
              return (List<RBS.Core.Model.V_OrderDetails>)Session[RBSKeys.SESSION_SHOPCAR_INFO];
 
        }

       [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult OrderTempDetail(FormCollection collection)
        { 
            var model = new RBS.Core.Model.V_OrderDetails()
            { 
                HCId = Convert.ToInt32(collection["HCId"]),
              /*  IsGuest = Convert.ToInt32(collection["IsGuest"]),*/
                CName = collection["CName"],
                Num = Convert.ToInt32(collection["Num"]),
                Price = Convert.ToDecimal(collection["Price"]),
              /*  UId = Convert.ToInt32(collection["UId"]),*/
                DisAmount = 0,
                State = 0
            };  
            var detailTemp = GetModelByCache(model);
             var jsonData=new JsonData
                 {
                     Success =true,
                     Data = detailTemp
                 };
             return Json(jsonData); 
        } 
        #region 删除订单

       [AcceptVerbs(HttpVerbs.Post)]
       public JsonResult DeleteOrderTempDetail(int id, int type)
       {
           /*JsonData jsonData = ApiRepository.Delete("api/user/OrderDetail/" + id + "?type=" + type);
           return Json(jsonData);*/ 

           var detailTemp = (List<RBS.Core.Model.D_Order_Details>)Session[RBSKeys.SESSION_SHOPCAR_INFO]; 
           var item = detailTemp.FirstOrDefault(c => c.HCId == id);  
           if(item!=null)
              detailTemp.Remove(item);

           if (type == 2)
           {
               detailTemp=new List<D_Order_Details>();
           } 
           Session[RBSKeys.SESSION_SHOPCAR_INFO] = detailTemp;
           var jsonData = new JsonData
           {
               Success = true,
               Data = detailTemp
           };
           return Json(jsonData);
       }


       [AcceptVerbs(HttpVerbs.Post)]
       public JsonResult GetOrderTempDetail(int uid, int oid)
       {
           var detailTemp = (List<RBS.Core.Model.V_OrderDetails>)Session[RBSKeys.SESSION_SHOPCAR_INFO];
           var jsonData = new JsonData
           {
               Success = true,
               Data = detailTemp
           };
           return Json(jsonData);
       }
        #endregion
         

        #region 饭局邀请
       public ActionResult Invite(int id = 1, int orderid=0,string kword = null)
       {
           const int pageSize = 10;

           var bll = new RBS.Core.BLL.U_Friends();
           // var admin = GetAdminInfo(); //取得当前管理员信息
           if (kword != null) kword = kword.Replace("'", "");
           var strTemp = new StringBuilder();
           if (!string.IsNullOrEmpty(kword))
           {
               //strTemp.Append(" and (H_UID like  '%" + kword + "%' or H_UserName like '%" + kword + "%')");
           }
           string strWhere = " and UserId=" + CurrentUser.Id + strTemp.ToString();
           const string orderby = " id  desc";
           var startIndex = id;

           int totalItems = 0; //要分页的总记录数
           DataTable dt = bll.GetList(pageSize, startIndex, strWhere, orderby, out totalItems).Tables[0];
           //PagedList构造函数 
           var list = IListDataSet.DataTableToIList<RBS.Core.Model.U_Friends>(dt);
           PagedList<RBS.Core.Model.U_Friends> arts = null;
           if (list != null)
               arts = new PagedList<RBS.Core.Model.U_Friends>(list, id, pageSize, totalItems);
           else
           {
               list = new List<RBS.Core.Model.U_Friends>();
               arts = new PagedList<RBS.Core.Model.U_Friends>(list, id, pageSize, totalItems);
           }

           ViewBag.OrderId = orderid;
           return View(arts);
       }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult InviteFriend(string ids,string orderid, string returnUrl)
        {
            string msg = "";
            var ret = new JsonReturnMessages(); 
            try
            {
                foreach (var id in ids.TrimEnd(',').Split(',').ToList())
                {
                    var model = new RBS.Core.Model.D_Guest
                        {
                            GuestId = Convert.ToInt32(id),
                            OrderId = Convert.ToInt32(orderid),
                            Status = 0
                        };
                    new RBS.Core.BLL.D_Guest().Add(model); 
                }
                 

                var orderModel = new RBS.Core.BLL.D_Order().GetModel(Convert.ToInt32(orderid));
                var guestList = new RBS.Core.BLL.V_Guest().GetModelList(Convert.ToInt32(orderid));  
                var ymb = guestList.Aggregate("", (current, guest) => current + (guest.Mobile + ",")); 
              
                string content = "您的朋友在[" + orderModel.HotelName + "]预定的饭局,邀请您参加！";
                smsMessage.Send(ymb.TrimEnd(','), content, 1, out msg);   
            }
            catch (Exception exception)
            {
                ret.IsSuccess = false;
                ret.Msg = "操作失败！";
                return Json(ret);
            } 
            ret.IsSuccess = true;
            ret.Msg = "操作成功";
            ret.Data = !string.IsNullOrEmpty(returnUrl) ? returnUrl : Url.Action("Invite");
            return Json(ret);
        }

        #endregion


        public ActionResult GoHotel(int id)
        {
            var model = new RBS.Core.BLL.Hotel.H_Hotels().GetModelByCache(id);

            var location=model.Location.Split(','); 
            ViewBag.lng = location[0];
            ViewBag.lat = location[1];
           
            return View(model);
        }


        /// <summary>
        /// 使用优惠券
        /// </summary>
        /// <param name="id"></param>
        /// <param name="hid"></param>
        /// <returns>返回列表</returns>
        public ActionResult OrderDeed(int id, int hid)
        { 
            var model = new OrderViewModel
            {
                OrderModel = new RBS.Core.BLL.D_Order().GetModel(id),
                OrderDetailsModel = new RBS.Core.BLL.V_OrderDetails().GetModelList("OrderId=" + id)
            };
            model.SeateName = new RBS.Core.BLL.Hotel.H_Hotel_Seat().GetModelByCache(Convert.ToInt32(model.OrderModel.DineTable)).Name;
            //总金额
            model.OrderModel.OrderAmount = model.OrderDetailsModel.Sum(c => c.Num * c.Price);
            var count = 0;
            //酒店优惠券信息
            DataTable dt = new RBS.Core.BLL.P_Advertis_Payment().GetList(10, 1, " and HotelId=" + model.OrderModel.H_Id + "", " ValidEndTime desc ", out count).Tables[0];
            model.HotelDeed = IListDataSet.DataTableToIList<RBS.Core.Model.P_Advertis_Payment>(dt);
            //食客信息
            if (model.OrderModel.U_Id > 0)
            {
                model.User = new RBS.Core.BLL.U_User().GetModelByCache(model.OrderModel.U_Id);
                model.UserIntegration = new RBS.Core.BLL.U_User_Integration().GetIntegralCount(model.OrderModel.U_Id);
                dt = new RBS.Core.BLL.P_Advertis_Payment().GetListByUser(10, 1, "and U_Id= " + model.User.Id + " and HotelId=" + model.OrderModel.H_Id + "  and ValidEndTime>=GETDATE()", " ValidEndTime desc ", out count).Tables[0];
                IListDataSet.DataTableToIList<RBS.Core.Model.P_Advertis_Payment>(dt);
                model.UserDeed = IListDataSet.DataTableToIList<RBS.Core.Model.P_Advertis_Payment>(dt);
            }
            model.Seetlement = new RBS.Core.Model.D_Settlement
                {
                    OrderAmount = model.OrderModel.OrderAmount,
                    Amount = model.OrderModel.OrderAmount
                };
            return View(model); 

        }
        [HttpPost]
        public ActionResult OrderDeed(FormCollection collection)
        { 
            return RedirectToAction("OrderList");
        }
    }
}
